package com.jiejie.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/seat")
public class SeatController1 {
    @Autowired
    private RedisTemplate redisTemplate;

    private DefaultRedisScript<Long> script;

    @PostConstruct
    public void init(){
        script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("niceyoo.lua")));
    }

    @GetMapping("/c1")
    public String test(String seats){//seats="1排4座,2排3座"
        String[] seatStr=seats.split(",");
        String rseat="";
        for (String seat:seatStr) {
            Object value=redisTemplate.opsForHash().get("seat",seat);
            if (!value.equals(0)){
                rseat=rseat.concat(seat);
            }
        }




        //锁住的是id对应的商品记录,锁住的是每个商品
        String key = "lock_"+seats;
        //声明一个uuid
        String uuid = UUID.randomUUID().toString().replace("-","");
        //获取锁
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key,uuid,1, TimeUnit.SECONDS);
        System.out.println(flag);
        if(flag){//获取锁成功
            //执行业务逻辑
            redisTemplate.opsForHash().putIfAbsent("seat",seats,1);
            redisTemplate.opsForHash().get("seat",seats);
            Object value = redisTemplate.opsForValue().get("num");
            // 如果是空直接返回
            if(value==null)
                return "error";
            // 不是空 如果说在这出现了异常！ 那么delete 就删除失败！ 也就是说锁永远存在！
            int num = Integer.parseInt(value + "");
            // 使num 每次+1 放入缓存
            redisTemplate.opsForValue().set("num", String.valueOf(++num));

//            try {
//                Thread.sleep(5000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

            Long execute = (Long) redisTemplate.execute(script, Arrays.asList(key),uuid);
            System.out.println("execute执行结果，1表示执行del，0表示未执行 ===== " + execute);
        }else{
            System.out.println("获取锁失败!");
            try {
                //获取锁失败、每隔0.1秒再获取
                Thread.sleep(100);
                test(seats);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "ok";
    }

}
